<!--
* description: 备件交期管理-物流时间设置
* author: zouzhu
* createdDate: 2021-01-28
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="tableCols"
      :dynamic-api-config="apiConfig"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible.sync="editPopupsVisible"
      :popups-state="editPopupsState"
    />
  </div>
</template>

<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/pa/sparepartsDeliveryManagement'
import Vue from 'vue'

export default {
  name: 'LogisticsTimeSetting',

  components: {
    OneTableTemplate,
    Edit: () => import('./addTime')
  },

  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      editPopupsVisible: false,
      editRowData: {},
      selectData: {},
      apiConfig: api.queryPartLogisticsTimeSetInfo,

      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'add',
          clickEvent: () => this.add(),
          text: '新增',
          position: 'left'
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'confirm',
          clickEvent: () => this.save(),
          text: '保存',
          position: 'right'
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: '重置',
          position: 'right'
        },
        {
          compKey: 'btnKey5',
          size: 'small',
          name: 'export',
          clickEvent: () => this.exportExcel(),
          text: this.$t('sys.button.export'),
          position: 'left'
        },
        {
          compKey: 'btnKey6',
          size: 'small',
          name: 'importTemplate',
          icon: 'iconfont icon-importTemplate',
          clickEvent: () => this.handFileListChange(),
          text: '导入',
          position: 'upload'
        },
        {
          compKey: 'btnKey7',
          type: 'text',
          size: 'small',
          name: 'importTemplateDownload',
          icon: 'iconfont  icon-importTemplateDownload',
          click: () => this.templateDownload(),
          text: 'Excel导入模板下载',
          position: 'left'
        }
      ],

      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '发货仓库：',
              codeField: 'warehouseId',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'warehouseId,warehouseName',
              customObj: {
                api: api.findWarehouseInfo,
                selectTye: '1'
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '收货网点：',
              codeField: 'dlrShortName',
              // textField: 'dlrFullName',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              isMul: false,
              isMust: true,
              dataToObject: {
                // oFields: 'dlrId,dlrShortName',
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '门店编码：',
                    codeField: 'dlrCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '门店名称：',
                    codeField: 'dlrFullName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'dlrCode',
                    label: '门店编码'
                  },
                  {
                    prop: 'dlrShortName',
                    label: '门店名称'
                  }
                ],
                formField: {
                  dlrId: '',
                  dlrCode: '',
                  dlrFullName: ''
                },
                returnField: {
                  prop: 'dlrShortName',
                  label: '门店名称'
                },
                // api: apis.queryStore
                api: {
                  APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/queryOrgDlrCodes.do'
                }
              }
            },
            // {
            //   compKey: 'compKey2',
            //   labelName: '收货网点：',
            //   codeField: 'dlrFullName',
            //   component: () => import('@/components/pa/salesStore'),
            //   type: 'inputText',
            //   isMul: false,
            //   isMust: true
            // },
            {
              compKey: 'compKey3',
              labelName: '运输方式：',
              codeField: 'transportModeId',
              textField: 'transportModeName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'transportModeId,transportModeName',
              customObj: {
                api: api.findTransportMode,
                selectTye: '1'
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            }
          ],

      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'logisticsDateId',
              label: '物流时间ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'warehouseId',
              label: '发货仓库ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'dlrId',
              label: '收货网点ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'transportModeId',
              label: '运输方式ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'warehouseName',
              label: '发货仓库'
            },
            {
              prop: 'dlrCode',
              label: '收货网点编码'
            },
            {
              prop: 'dlrShortName',
              label: '收货网点名称'
            },
            {
              prop: 'receiptTypeCn',
              label: '收货地类型'
            },
            {
              prop: 'transportModeName',
              label: '运输方式'
            },
            {
              prop: 'transportTime',
              label: '运输时间',
              isComponent: true,
              comps: [
                {
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'transportTime',
                  component: () => import('@/components/org/commonInput'),
                  type: 'inputText'
                }
              ]
            },
            {
              prop: 'workTime',
              label: '备货周期（月）',
              isComponent: true,
              comps: [
                {
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'workTime',
                  component: () => import('@/components/org/commonInput'),
                  type: 'inputText'
                }
              ]
            },
            {
              prop: 'remark',
              label: '备注',
              isComponent: true,
              comps: [
                {
                  compKey: 'compKey5' + this.$utils.generateId(),
                  codeField: 'remark',
                  component: () => import('@/components/org/commonInput'),
                  type: 'inputText'
                }
              ]
            }
          ],

      formField: this.$utils.getFormField(this, {
        warehouseId: '',
        warehouseCode: '',
        dlrShortName: '',
        transportModeCode: '',
        logisticsDateId: '',
        dlrId: '',
        dlrFullName: '',
        transportModeId: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectData = selection

          this.handleSelectionChange(selection)
        }
      }
    }
  },

  mounted() {
    this.queryTable(1)
  },

  methods: {

    add() {
      this.editPopupsState = 'add'
      this.editPopupsVisible = true
    },

    // 保存
    save() {
      // debugger
      const queryObj = {
        type: 'mutation',
        apiConfig: api.updatePartLogisticsTimeSet,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          dataInfo: this.selectData
        }
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg
          })
          this.queryTable(1)
        } else {
          this.$message({
            message: response.msg
          })
        }
        this.queryTable(1)
      })
    },

    // 导入
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType !== 'xls' && fileType !== 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      const that = this
      const url = api.logisticsImportExcel.APIUrl
      that
        .$requestUpload(url, param)
        .then(response => {
          loading.close()
          if (response.result === '1') {
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            that.queryTable()
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch(_ => {})
    },

    // 模板下载
    templateDownload() {
      this.$requestAPI({
        variables: { dataType: 'excel' },
        apiUrl: api.logisticsDownloadTemplate.APIUrl
      }).then(res => {
        this.$utils.downloadFile(res, '备件物流时间设置导入模板下载.xlsx')
      })
    },

    // 导出
    exportExcel() {
      const fileName = this.$utils.fileNameWithTime('备件物流时间设置.xlsx')
      this.$requestAPI({
        apiUrl: api.logisticsExportDetails.APIUrl,
        variables: { dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>
